<?php
/**
 * Created by PhpStorm.
 * FileName: BaseController.class.php
 * User: Administrator
 * Date: 2018/5/22
 * Time: 16:09
 */

namespace WeiXin\Controller;

use Common\Lib\Util\ToolUtil;
use Think\Controller;

class BaseController extends Controller {

    private $userModel;

    public function __construct() {
        parent::__construct();
        $this->userModel = M('Users');
        $this->assign('serverName',SERVER_NAME.__ROOT__);
        $this->assign('IMG_PATH',C('IMG_PATH'));
        if (strcasecmp(ToolUtil::getBrowser(),'WeiXin') === 0) {
            $this->assign('isWeiXin',1);
            $this->getUserInfo();
        }
    }

    protected function getUserInfo() {
        vendor('WeiXinSDK.wechat','','.class.php');
        $options = array(
            'appid' => C('appId'), //填写高级调用功能的app id
            'appsecret' => C('appSecret') //填写高级调用功能的密钥
        );
        $weObj = new \Wechat($options);
        $userId = session('userId');
        $isExist = false;
        if ($userId) {
            $count = $this->userModel->where(array('id' => $userId))->count();
            $isExist = $count > 0 ? true : false;
        }
        if (!$userId || $isExist === false) {
            if(!empty($_REQUEST['code'])){
                $res = $weObj->getOauthAccessToken();
                $result = $weObj->getOauthUserinfo($res['access_token'], $res['openid']);
                if ($result) {
                    $this->addUser($result,$res['openid']);
                }
            }else{
                $callback = SERVER_NAME.U('WeiXin/'.CONTROLLER_NAME.'/'.ACTION_NAME, $_REQUEST);
                $url = $weObj->getOauthRedirect($callback, $state = '', $scope = 'snsapi_userinfo');
                header("Location:".$url);
            }
        }
        $this->{ACTION_NAME}();
        die();
    }

    private function addUser($result,$openid)
    {
        $data = array(
            'user_name' => '',
            'real_name' => $this->removeEmoji($result['nickname']),
            'openid' => $result ["openid"],
            'role_id' => C('WEIXIN_ROLE_ID'),
            'gender' => $result['sex'],
            'avatar'=> $result['headimgurl'],
        );
        $user = $this->userModel->where(array('openid' => $result['openid']))->find();
        if (empty($user)) {
            $id = $this->userModel->add($data);
            if($id){
                $_SESSION['openId'] = $openid ;
                $_SESSION['userId'] = $id;
                $_SESSION['userName'] = $result['nickname'];
            }

        }else{
            session('userId',$user['id']);
            session('openId',$user['openid']);
            session('userName',$result['nickname']);
            $this->userModel->where(array('id'=>$user['id']))->save($data);
        }
    }
    
    private function removeEmoji($str){
        $message = json_encode($str);
        return json_decode(preg_replace("#(\\\ud[0-9a-f]{3})#i", "", $message),true);
    }

}